package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RequestMappingHandlerMapping rmhm;

    @Override
    public void reload() {
        //获取数据库中已存在的所有权限对象
        List<Permission> permissions = permissionMapper.selectAll();
        Set<String> permissionSet = new HashSet<>();
        if (permissions != null){
            for (Permission permission : permissions) {
                permissionSet.add(permission.getExpression());
            }
        }
        //获取所有控制器中的所有映射方法集合
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> values = handlerMethods.values();
        //遍历所有的映射方法
        for (HandlerMethod method : values) {
            //判断方法上是否存在权限注解
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if(methodAnnotation != null){
                //判断代码中的权限是否已经存在,不存在插入,存在筛选出来
                if(!permissionSet.contains(methodAnnotation.expression())){
                    Permission permission = new Permission();
                    permission.setName(methodAnnotation.name());
                    permission.setExpression(methodAnnotation.expression());
                    permissionMapper.insert(permission);
                }else{
                    permissionSet.remove(methodAnnotation.expression());
                }
            }
        }
        //删除所以筛选出来的废弃权限并删除
        for (String expression : permissionSet) {
            permissionMapper.deleteExpression(expression);
        }
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Permission> list = permissionMapper.queryList(qo);
        return new PageInfo<>(list);
    }

}
